package mapper

import (
	"encoding/json"
	"reflect"

	"gitee.com/rainsuperman/mapper_orm/mapper_core"
)

type Page[T any] struct {
	Page   int   `json:"page"`    // 页码
	Size   int   `json:"size"`    // 每页数量
	Total  int64 `json:"total"`   // 总数量
	Record []T   `json:"records"` // 数据
}

type DbEntity interface {
	TableName() string
}

// 默认配置信息
var config = &mapper_core.MapperConfig{
	IdColumnName:        "id",
	MarkDelColumnName:   "del",
	JoinBaseTableAsName: "a",
	MaxPageNum:          1000,
}

// 获取配置信息
func GetConfig() *mapper_core.MapperConfig {
	return config
}

// 指针转换
func Ptr[T any](v T) *T {
	return &v
}

func MapToStruct[T any](m map[string]any) (*T, error) {
	var t T
	mjson, err := json.Marshal(m) //转json
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(mjson, &t)
	if err != nil {
		return nil, err
	}
	return &t, nil
}

func MapsToStructs[T any](maps []map[string]any) ([]T, error) {

	mjson, err := json.Marshal(maps) //转json
	if err != nil {
		return nil, err
	}
	var tt []T

	err = json.Unmarshal(mjson, &tt)
	if err != nil {
		return nil, err
	}
	return tt, nil
}

// 获取结构体字段值
func getValue(fieldName string, reflectValue reflect.Value) *any {

	value := reflectValue.FieldByName(fieldName)

	if value.IsNil() {
		return nil
	}

	if value.Type().Kind().String() == "ptr" {
		v := value.Elem().Interface()
		return &v
	}
	v := value.Interface()
	return &v
}
